<!DOCTYPE html>
<html>
<head>
    <title>E姐姐随笔生成</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>
<body style="background-color:#fffbf6">
    {% include 'top_bar_ej.html' %}
    <h4>E姐姐随笔生成</h4>
    <div id="container" style="display:flex;background-color:#fffbf6 ;text-align: center; justify-content: center; width: 400px;flex-wrap: wrap; ">
        <div id="date" style="color:rgb(171, 176, 179); font-size:20px; margin-bottom: 10px;"></div>
    </div>

    <div><h3><span id="start_date_txt">· 请选择日期</span>  <input id='start_date' type='date' onchange="checkSuiBiPic();refresh();"></h3></div>    
    <div id="picMsg"></div>

    <div><h3>· 选择文件</h3>
        <label for="date_or_prd">
            <h4><input type='radio' name="fn" value="1" onclick=hideOrDisplayEndDate() checked> 文件1 <input type='radio' name="fn" value="2" onclick=hideOrDisplayEndDate()> 文件2</h4>            
        </label>
    </div>

    <div id="compPicBox1">
        <h3>上传图片</h3>
        <input type="file" name='image' id="pic" accept="image/*" style="display: none;">
        <div id="uploadMsg" ></div>
        <button id='browseButton' onclick="openFileBrowser();" style="margin-top:20px;">浏览</button>
        <button id="upload" onclick="uploadFileSuiBi();">上传</button>
        <input type="file" name='image' id="fileInput" accept="image/*" style="display: none;">
    </div>
    
    <!-- <div id="end_date_block"><h3>· 请选择结束日  <input id='end_date' type='date'></h3></div> -->

    <hr>
    <div id="prompt" class="prompt">
    </div>
    <div>
        <button id="submit" onclick=submit()>生成随笔文案</button>&nbsp;&nbsp;<button id="refresh" onclick="refresh();">刷新看是否已完成</button>
    </div>

   

    <div id="dl" style="margin-top:10px;display:none;">
        <a id="downloadLink" href="#" onclick="generateDownloadLink()">下载文件</a>
    </div>

    <div id="resDateList" style="margin-top:30px;"></div>

    
    <script src="../static/js/common.js"></script>
    <script>
        let dates;
        let selectedFile;
        document.addEventListener('DOMContentLoaded',function(){
            showDateandWeekDay();
            selectToday('start_date','date');

            checkSuiBiPic();

            document.getElementById('fileInput').addEventListener('change', handleFileSelection);
                const fileInput = document.getElementById("fileInput");
                fileInput.addEventListener("change", handleFileSelection);
                refresh();

            
        });

        function refresh(){       
            const startDate=document.getElementById('start_date').value;
            const resDateList=document.getElementById('resDateList');
            resDateList.innerHTML='';
            const data={       
                'start_date':startDate
            }
            fetch('/check_suibi_files',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if(data['res']==='ok'){
                        console.log(data);
                        
                        const sel=document.createElement('select');
                        data['data'].forEach(ele => {        
                            zipAndDownload(ele);             
                            // const opt=document.createElement('option');
                            // opt.value=ele;
                            // opt.text=ele;
                            // opt.addEventListener('change',zipAndDownload(ele))
                            // sel.appendChild(opt);           
                                             
                        });
                        // resDateList.appendChild(sel);
                    }else{
                        resDateList.innerHTML='该日期还没有生成随笔视频';
                    }
                    
                })
                .catch(error=>{
                    console.log(error);
                })

        }

        function zipAndDownload(dateInput){
            const resDateList=document.getElementById('resDateList');
            const dlDiv=document.createElement('div');
            const a=document.createElement('a');
            const baseUrl='{{ url_for("zip_and_download_suibi") }}';
            a.innerText=`${dateInput}随笔视频下载`;
            a.href=`${baseUrl}?dateInput=${dateInput}`;
            dlDiv.appendChild(a);
            resDateList.appendChild(dlDiv);
        }

        function openFileBrowser() {
            document.getElementById('fileInput').click();
        }

        function newSelectedName(name){ 
            const cusName=document.getElementById('cusName').value;
            const dateSelect=dateToString(document.getElementById('date').value,'digit8');
            const fileExtension = name.split('.').pop();
            const filename = insIdPage + '-' + cusName + '-' + dateSelect + '.' + fileExtension;
            return filename
        }

        function checkSuiBiPic(){
            const picMsg=document.getElementById('picMsg');
            picMsg.innerHTML='';
            const startDate=document.getElementById('start_date').value;
            fetch('/check_suibi_pic',{
                method: 'POST',
                headers:{
                    'Content-Type':'application/json'
                },
                body: JSON.stringify({'dateInput':startDate})
            })
            .then(response=>response.json())
            .then(data=>{
                console.log(data)
                if(data['res']==='ok'){
                    picMsg.innerHTML=`<span style='color:green;padding-left:20px;'>该日期已有${data['max_num']}张随笔图片</span>`;
                }else{
                    picMsg.innerHTML=`<span style='color:green;padding-left:20px;'>该日期${data['error']}</span>`;
                }
            })
            .catch(error => {
                console.log('Error:',error);
            });
            
        }

        function handleFileSelection(event) {
            selectedFile = event.target.files[0];
            const uploadMsg=document.getElementById('uploadMsg');
            // const newFileName=newSelectedName(selectedFile.name);
            uploadMsg.textContent=`已选择文件：${selectedFile.name}`
           
        }

        function uploadFileSuiBi() {
            document.getElementById('uploadMsg').textContent = '';
            if (!selectedFile) {
                alert("请选择要上传的图片");
                return;
            }

            const dateInput=document.getElementById('start_date').value;
            // const newFileName=newSelectedName(selectedFile.name);
            const newFileName=selectedFile.name;
            console.log(selectedFile,newFileName)
  
            
            const url = "/upload_pic_suibi?filename=" + encodeURIComponent(newFileName)+"&date_input=" + encodeURIComponent(dateInput);

            let formData = new FormData();
            formData.append("file", selectedFile); 
            formData.append("filename", newFileName);
            // console.log(url)

            let xhr = new XMLHttpRequest();
            xhr.open("POST", url);
            document.getElementById('uploadMsg').textContent = `${newFileName} 正在上传...`;
            xhr.onload = function() {
                console.log('xhr status:',xhr.status)
                const resp = JSON.parse(xhr.responseText);
                const responseMsg = resp.message;
                const numAfterUp=resp.max_num;
                // console.log('message:',errorMessage)
                if (xhr.status === 200) {
                    document.getElementById('uploadMsg').textContent=`${newFileName} 上传成功`;
                    // console.log(responseMsg,numAfterUp)
                    const picMsg=document.getElementById('picMsg');
                    picMsg.innerHTML=`<span style='color:green;padding-left:20px;'>该日期已有${numAfterUp}张随笔图片</span>`;
                  
                    // alert("上传成功");
                } else {
                    document.getElementById('uploadMsg').textContent='上传失败，请联系管理员。'+responseMsg
                    alert("上传失败，请联系管理员。错误："+responseMsg);
                }
            };
            xhr.send(formData);
        }
    
        function generateDownloadLink() {
            const dateInput=document.getElementById('start_date').value
            // const fn = selectedFile.name; // 动态获取param1的值
            const link = document.getElementById('downloadLink');
            link.href = '{{ url_for("zip_and_download_suibi") }}' + '?dateInput=' + encodeURIComponent(dateInput);
            
            link.addEventListener('click',hideDownload);
            // hideDownload();
        }

        function hideDownload(){
            const dl=document.getElementById('dl');
            // const prompt=document.getElementById('prompt');
            // prompt.innerText='';
            // prompt.style.display='block';
            dl.style.display='none';
        }
    
        function hideDownload(){
            const dl=document.getElementById('dl');
            const prompt=document.getElementById('prompt');
            prompt.innerText='';
            prompt.style.display='block';
            dl.style.display='none';
        }

        function sameEndDate(){
            document.getElementById('end_date').value=document.getElementById('start_date').value;
        }

        function showDateandWeekDay(){
            const dateBlock=document.getElementById('date');
                const today=new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                // 获取星期几的数值
                const dayOfWeek = today.getDay();
                // 将星期几的数值转换为中文
                let weekDayChinese = '';
                switch (dayOfWeek) {
                case 0:
                    weekDayChinese = '星期日';
                    break;
                case 1:
                    weekDayChinese = '星期一';
                    break;
                case 2:
                    weekDayChinese = '星期二';
                    break;
                case 3:
                    weekDayChinese = '星期三';
                    break;
                case 4:
                    weekDayChinese = '星期四';
                    break;
                case 5:
                    weekDayChinese = '星期五';
                    break;
                case 6:
                    weekDayChinese = '星期六';
                    break;
                default:
                    weekDayChinese = '未知';
                }
                dateDisplay=`${year} 年 ${month} 月 ${day} 日
                            ${weekDayChinese}`; 
                dateBlock.innerText=dateDisplay;
        }

        function hideOrDisplayEndDate(){
            const dateOrPrd=document.querySelector('input[name="date_or_prd"]:checked').value;
            const endDateBlock=document.getElementById('end_date_block');
            const startDateTxt=document.getElementById('start_date_txt');

            // 单日
            if(dateOrPrd==='0'){            
                endDateBlock.style.display='None';
                startDateTxt.innerText='· 请选择日期'
            // 多日
            }else{
                endDateBlock.style.display='block';
                startDateTxt.innerText='· 请选择起始日'
            }
        }
        
        function submit(){
            const startDate=document.getElementById('start_date').value;
            const prompt=document.getElementById('prompt');
            const fnNum=document.querySelector('input[name="fn"]:checked').value;
            // prompt.innerText='正在处理，请等待。'
            // console.log(startDate,endDate)   
            prompt.innerText='正在生成随笔视频。。。时间较长，请等待。'

            fetch('/generate_suibi',{
                    method: 'POST',
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body: JSON.stringify({'dateInput':startDate,'fnNum':fnNum})
                    })
                    .then(response => response.json())
                    .then(data => {
                        res=data.res;      
                        console.log(res)              
                        if(res==='ok'){
                            // document.getElementById('dl').style.display='block';
                            refresh();
                            console.log('new zip back')
                            // 修改提示只有在没有错误发生时才生效
                            if (prompt.innerText === '正在生成随笔视频。。。时间较长，请等待。') {
                                prompt.style.display = 'none';
                            }
                        }else{
                            console.log('error',data.error)
                            prompt.innerText = data.error;
                            alert('随笔生成错误'+'\n'+data.error)
                        }
                        

                    })
                    .catch(error => {
                        console.log('Error:',error);
                        prompt.innerText = error;
                        document.getElementById('dl').style.display='none';});
            

        }

    
    

    </script>
</body>